﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DomainDriver.DomainModeling.StorageManagers.EntityFrameworkStorage
{
    public class CombinedKeyBasedEqualityComparer<T> : IEqualityComparer<T>
        where T : IEfStorableObject
    {
        public virtual bool Equals(T x, T y)
        {
            if ((x == null) || (y == null))
            { throw new InvalidOperationException("The objects to compare must not be null."); }

            object[] xKey = x.EF_CombinedId;
            object[] yKey = y.EF_CombinedId;

            for (int i = 0; i < xKey.Length; i++)
            {
                object xKeyPart = xKey.ElementAt(i);
                object yKeyPart = yKey.ElementAt(i);

                if (!xKeyPart.Equals(yKeyPart))
                { return false; }
            }
            return true;
        }

        public virtual int GetHashCode(T obj)
        {
            object[] key = obj.EF_CombinedId;
            string keyAsString = string.Empty;

            for (int i = 0; i < key.Length; i++)
            {
                object keyPart = key.ElementAt(i);

                if (keyAsString == string.Empty)
                { keyAsString += keyPart.ToString(); }
                else
                { keyAsString += ", " + keyPart.ToString(); }
            }
            return keyAsString.GetHashCode();
        }
    }
}